package cn.achuan.spring.springcloud.demo;

import cn.achuan.spring.springcloud.demo.product.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 远程事件监听
 */
@Component
public class ProductEventListener implements ApplicationListener<ProductEvent> {
    private static final Logger logger = LoggerFactory.getLogger(ProductEventListener.class);

    @Autowired
    private ProductService productService;

    @Override
    public void onApplicationEvent(ProductEvent productEvent) {
        if (ProductEvent.P_UPDATE.equalsIgnoreCase(productEvent.getAction())) {
            logger.debug("收到商品变更事件，商品货号: {}", productEvent.getItemCode());
            // 重新获取该商品信息
            Product product = this.productService.loadByItemCode(productEvent.getItemCode());
            if (product != null)
                logger.debug("重新获取到的商品信息为:{}", product);
            else
                logger.debug("货号为:{} 的商品不存在", productEvent.getItemCode());
        } else if (ProductEvent.P_DELETE.equalsIgnoreCase(productEvent.getAction())) {
            logger.debug("收到商品删除事件，所要删除商品货号为: {}", productEvent.getItemCode());
        } else {
            logger.debug("收到未知商品事件: {}", productEvent);
        }
    }
}